package cn.tedu.travelsystem.controller;


import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/map")
@CrossOrigin(origins = "*")
public class BaiduMapController {
    private static final String BAIDU_URL = "https://api.map.baidu.com/directionlite/v1/driving?";
    private static final String AK = "0xoDDSNdRUlazfXkxQNpvYqSBgBRu1Fx";

    @GetMapping("/route")
    public String getDrivingRoute(
            @RequestParam String origin,
            @RequestParam String destination
    ) {
        try {
            Map<String, String> params = new LinkedHashMap<>();
            params.put("origin", origin);               // 示例：40.01116,116.339303
            params.put("destination", destination);     // 示例：39.936404,116.452562
            params.put("ak", AK);

            String queryUrl = buildUrl(BAIDU_URL, params);

            // 创建连接并读取返回结果
            HttpURLConnection connection = (HttpURLConnection) new URL(queryUrl).openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();

            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\":500,\"message\":\"Error calling Baidu Map API: " + e.getMessage() + "\"}";
        }
    }

    private String buildUrl(String baseUrl, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(baseUrl);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(UriUtils.encode(entry.getValue(), "UTF-8"))
                    .append("&");
        }
        sb.deleteCharAt(sb.length() - 1); // 去除最后一个&
        return sb.toString();
    }
}
